<?php
/**
 * Created by PHPStorm
 * User: xiest
 * Date: 2021/4/19
 * Email: <939369942@qq.com>
 */
namespace basic\services;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use basic\traits\Error;
use think\exception\ValidateException;
use think\facade\Config;

class SmsService
{
    use Error;

    protected $config = [];

    public function __construct($config)
    {
        $this->config = $config;
        $this->init($config);
    }

    public function init($config)
    {
//        $AccessKeyId = $config['sms_access_key_id'] ?? '';
//        $AccessKeySecret = $config['sms_access_key_secret'] ?? '';
//        $RegionId = $config['sms_region_id'] ?? '';
//
//        AlibabaCloud::accessKeyClient($AccessKeyId, $AccessKeySecret)
//            ->regionId($RegionId)
//            ->asDefaultClient();
    }


    public static function create()
    {
        $config = systemConfig(['sms_access_key_id','sms_access_key_secret','sms_region_id','sms_sign_name']);
        // $templates = systemGroupData('sms_template_list');
        $config['template_map'] = config('sms.aliyun.template_map');
        /*foreach ($templates as $template) {
            $config['template_map'][$template['template_alias']] = $template[''];
        }*/

        return new static($config);
    }


    /**
     * 发短信
     * @param array $data = [
     *      'templateId'=>'',
     *       'phone'    =>'',
     *       ....
     *  ]
     * @throws \Exception
     * User: xiest
     * Date: 2021/4/20
     */
    public function sendMessage(array $data)
    {
        //return null;
        if(!isset($data['templateId'])||!$data['templateId'])
            throw new \Exception('模板id不存在');

        switch ($data['templateId'])
        {
            case 'VERIFY_CODE':

                $content =  "【鑫尚信息】您的验证码是{$data['code']}。如非本人操作，请忽略本短信"; //"【汇客私域】验证码：{$data['code']},有效期10分钟!";
                $url =  "https://api.smsbao.com/sms?u=xin32588&p=bba2f9dc83364b3ea42be156405c7bc0&m={$data['phone']}&c=$content";
                $rs = file_get_contents($url);
               // var_dump($rs);
                $sendData['code'] = $data['code'];
                return true;
                break;
            default:
                $sendData = [];
        }

        $service = self::create();
        $rs = $service->send($data['phone']??'',$data['templateId'],$sendData);
        if($rs !== true) throw new \Exception($service->getError());
        return $rs;
    }


    public function send(string $phone,string $templateId,array $data=[])
    {
        if(empty($phone)) return $this->setError('Mobile number can not be empty!');

        try {
            $templateCode = $this->getTemplateCode($templateId);
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'PhoneNumbers'=>$phone,
                        'SignName'=>$this->config['sms_sign_name']??'',
                        'RegionId' => $this->config['sms_region_id']??'',
                        'TemplateCode' => $templateCode,
                        'TemplateParam'=> count($data)?json_encode($data):'',
                    ],
                ])
                ->request();
            // print_r($result->toArray());
        } catch (ClientException $e) {
            return $this->setError($e->getMessage());
        } catch (ServerException $e) {
            return $this->setError($e->getMessage());
        }

        return true;
    }


    public function getTemplateCode($templateId)
    {
        return $this->config['template_map'][$templateId]??"";
    }

}